﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.DispatchCommand;
using ProductionManagement.Infrstructre.lmp;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.DIspatchCommandHandlers
{
    public class DelDiapatchCommandHandlers : IRequestHandler<DelDiapatchCommand, int>
    {
        private readonly IDispatchRepository _dispatch;
        private readonly IDisProductRepository _disProduct;
        private readonly IDisMaterialRepository _disMaterial;
        private readonly IMapper _mapper;
        ISqlSugarClient db;


        public DelDiapatchCommandHandlers(IDispatchRepository dispatch, IDisProductRepository disProduct, IDisMaterialRepository disMaterial, IMapper mapper, ISqlSugarClient db)
        {
            _dispatch = dispatch;
            _disProduct = disProduct;
            _disMaterial = disMaterial;
            _mapper = mapper;
            this.db = db;
        }
        public async Task<int> Handle(DelDiapatchCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var list = (await _dispatch.GetAll()).Where(x => request.DispatchId.Contains(x.DispatchId)).ToList();
                foreach (var material in list)
                {
                    material.IsDel = true;
                    material.DelName = request.DelName;
                    material.DelTime = DateTime.Now;
                    var item = (await _disProduct.GetAll()).Where(x => x.DNumber == material.DNumber).ToList();
                    foreach (var subpiece in item)
                    {
                        subpiece.IsDel = true;
                        subpiece.DelName = request.DelName;
                        subpiece.DelTime = DateTime.Now;
                        await _disProduct.UpdAsync(subpiece);
                    }
                    await _dispatch.UpdAsync(material);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            finally
            {
                db.Ado.Close();
            }
            return 1;
        }
    }
}
